package com.joyveb.securitycheck.pkcs11.ssldemo;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLServerSocket;
import javax.net.ssl.TrustManagerFactory;

/**
 * 
 * @author yangqiju
 *http://yangqiju.github.io/ssl-tls-ukey-pkcs11/
 */
public class Server {

	private static final String SERVER_KEY_STORE_PASSWORD = "password";
	private static final String SERVER_TRUST_KEY_STORE_PASSWORD = "password";
	private static final int port = 10036;
	
	public static void main(String[] args) throws Exception {
			String ksFilePath =  Server.class.getResource("server.pfx").getFile();
			String tsFilePath  = Server.class.getResource("serverTS.jks").getFile();
			
			SSLContext ctx = SSLContext.getInstance("TLS");
			KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
			TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
			KeyStore ks = KeyStore.getInstance("PKCS12");
			KeyStore tks = KeyStore.getInstance("JKS");
			ks.load(new FileInputStream(ksFilePath), SERVER_KEY_STORE_PASSWORD.toCharArray());
			tks.load(new FileInputStream(tsFilePath), SERVER_TRUST_KEY_STORE_PASSWORD.toCharArray());
			kmf.init(ks, SERVER_KEY_STORE_PASSWORD.toCharArray());
			tmf.init(tks);
			ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
			SSLServerSocket serverSocket = (SSLServerSocket) ctx.getServerSocketFactory().createServerSocket(port);
			serverSocket.setNeedClientAuth(true);
			
			while (true) {
				try {
					Socket s = serverSocket.accept();
					InputStream input = s.getInputStream();
					OutputStream output = s.getOutputStream();
					BufferedInputStream bis = new BufferedInputStream(input);
					BufferedOutputStream bos = new BufferedOutputStream(output);
					byte[] buffer = new byte[20];
					bis.read(buffer);
					System.out.println(new String(buffer));
					bos.write("handshake success.".getBytes());
					bos.flush();
					s.close();
				} catch (Exception e) {
					System.out.println(e);
				}
			}
	}
}
